package com.zhuhjay.service.system.wxmp.strategy.message;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.StrUtil;
import com.zhuhjay.common.redis.util.RedisUtils;
import com.zhuhjay.common.web.enums.MatchingMode;
import com.zhuhjay.common.wxmp.builder.TextBuilder;
import com.zhuhjay.service.system.model.entity.SystemOauth;
import com.zhuhjay.service.system.model.entity.SystemUser;
import com.zhuhjay.service.system.service.SystemOauthService;
import com.zhuhjay.service.system.service.SystemUserService;
import com.zhuhjay.service.system.wxmp.strategy.AbstractMessageStrategy;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import static com.zhuhjay.common.base.constant.CacheConstant.WX_LOGIN_CODE_PREFIX;
import static com.zhuhjay.service.system.enums.OauthTypeEnum.WECHAT;

/**
 * @author ZhuHJay
 * @date 2023/11/12 21:36
 */
@Lazy
@Component
@RequiredArgsConstructor
public class LoginMessage extends AbstractMessageStrategy {

    private final SystemUserService userService;
    private final SystemOauthService oauthService;

    @Override
    public boolean support(String content) {
        return content.startsWith("登录");
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, WxMpService wxMpService) {
        String code = wxMessage.getContent().substring(2).trim();
        String key = WX_LOGIN_CODE_PREFIX + code;
        String cache = RedisUtils.getCache(key);
        // null 代表缓存不在 ""代表未登录
        if (cache == null || StrUtil.isNotBlank(cache)) {
            return new TextBuilder().build("授权码无效", wxMessage, wxMpService);
        }
        // 该openid是否绑定账号
        String openid = wxMessage.getFromUser();
        StrBuilder sb = new StrBuilder("登录成功，请等待客户端响应！");
        SystemOauth oauth = oauthService.lambdaQuery().eq(SystemOauth::getOpenId, openid).one();
        if (oauth == null) {
            // 创建账号并绑定(返回的用户信息密码为明文)
            SystemUser user = userService.createAccount(WECHAT, openid);
            oauth = oauthService.createOauth(user.getId(), WECHAT, openid);
            sb.append("\n检测到您第一次绑定，已为您自动创建账号, 信息如下：")
                    .append("\n- 用户名 => ").append(user.getUsername())
                    .append("\n- 密码 => ").append(user.getPassword())
                    .append("\n收到后请及时修改密码！")
                    .append("\n如若需要修改用户名则回复【用户名xxx】即可(不用空格, 仅有一次修改机会)！")
                    .append("\n用户名规则为 => ").append(MatchingMode.Username.getMessage());
        } else {
            SystemUser user = userService.getById(oauth.getUserId());
            if (user.getUsername().startsWith(WECHAT.getType() + '_')) {
                sb.append("\n如若需要修改用户名则回复【用户名xxx】即可(不用空格, 仅有一次修改机会)！")
                        .append("\n用户名规则为 => ").append(MatchingMode.Username.getMessage());
            }
        }
        // 已经绑定, 查询用户id
        Integer userId = oauth.getUserId();
        // 将用户id存入缓存中
        RedisUtils.setCache(key, userId);
        return new TextBuilder().build(sb.toString(), wxMessage, wxMpService);
    }

}
